<template>
  <!-- eslint-disable vue/no-unused-components -->
  <div class="graph-analysis-container">
    <!-- 顶部选项卡导航 - 现代化设计 -->
    <div class="main-tabs-container">
      <div class="main-tabs-wrapper">
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'supplyChain' }" 
          @click="handleTabClick({props: {name: 'supplyChain'}})"
        >
          <el-icon class="tab-icon"><Link /></el-icon>
          <span class="tab-text">产业链上下游</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'industryComprehensive' }" 
          @click="handleTabClick({props: {name: 'industryComprehensive'}})"
        >
          <el-icon class="tab-icon"><TrendCharts /></el-icon>
          <span class="tab-text">行业企业综合分析</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'companyRisks' }" 
          @click="handleTabClick({props: {name: 'companyRisks'}})"
        >
          <el-icon class="tab-icon"><Warning /></el-icon>
          <span class="tab-text">企业风险</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'regionStats' }" 
          @click="handleTabClick({props: {name: 'regionStats'}})"
        >
          <el-icon class="tab-icon"><DataBoard /></el-icon>
          <span class="tab-text">区域企业统计</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'productChain' }" 
          @click="handleTabClick({props: {name: 'productChain'}})"
        >
          <el-icon class="tab-icon"><Goods /></el-icon>
          <span class="tab-text">产品链技术决策支持</span>
        </div>
      </div>
    </div>
    <!-- 主内容区域 - 左右两栏布局 -->
    <div class="main-content-layout">
      <!-- 左侧查询表单 -->
      <el-card class="query-card" shadow="hover">
        <template v-if="activeTab === 'supplyChain'">
          <el-form :model="supplyChainForm" label-position="top">
            <el-row>
              <el-col :span="24">
                <el-form-item label="公司名称">
                  <el-autocomplete
                    v-model="supplyChainForm.companyName"
                    :fetch-suggestions="queryCompanies"
                    placeholder="请输入公司名称"
                    clearable
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="查询深度">
                  <el-slider
                    v-model="supplyChainForm.depth"
                    :min="1"
                    :max="5"
                    :step="1"
                    :marks="{1:'1', 2:'2', 3:'3', 4:'4', 5:'5'}"
                    class="form-slider"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" style="text-align: center; margin-top: 16px;">
                <el-button type="primary" @click="handleQuery" class="query-button">
                  <el-icon><Search /></el-icon> 查询
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </template>
        <!-- 行业内企业查询 -->
        <template v-else-if="activeTab === 'industryComprehensive'">
          <el-form :model="industryComprehensiveForm" label-position="top">
            <el-form-item label="行业名称">
              <el-autocomplete
                v-model="industryComprehensiveForm.industryName"
                :fetch-suggestions="queryIndustrySearch"
                placeholder="请输入行业名称"
                clearable
                style="width: 100%"
                @select="handleIndustryComprehensiveSelect"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryIndustryComprehensive" :loading="loading">
                <el-icon><Search /></el-icon> 查询分析
              </el-button>
            </el-form-item>
            <!-- 分析说明 -->
            <el-alert
              title="行业企业综合分析功能可以全面了解行业发展状况、高新技术企业与普通企业对比，以及企业创新能力评估"
              type="info"
              :closable="false"
            />
          </el-form>
        </template>
        <!-- 企业风险查询 -->
        <template v-else-if="activeTab === 'companyRisks'">
          <el-form :model="riskForm" label-position="top">
            <el-form-item label="行业名称">
              <el-autocomplete
                v-model="riskForm.industryName"
                :fetch-suggestions="queryIndustrySearch"
                placeholder="请输入行业名称"
                clearable
                style="width: 100%"
                @select="handleRiskIndustrySelect"
              />
            </el-form-item>
            <el-form-item label="最小风险数量">
              <el-input-number v-model="riskForm.minRiskCount" :min="1" :max="100" style="width: 100%" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryCompanyRisks" :loading="loading">
                <el-icon><Search /></el-icon> 查询分析
              </el-button>
            </el-form-item>
          </el-form>
        </template>
        <!-- 高新技术企业查询 -->
        <template v-else-if="activeTab === 'regionStats'">
          <div style="padding: 20px;">
            <el-alert
              title="区域企业统计功能可以帮您了解各省份企业的分布情况、员工数量、注册资本和高新技术企业数量等关键指标"
              type="info"
              :closable="false"
              style="margin-bottom: 20px;"
            />
            
            <div style="text-align: center; margin-top: 30px;">
              <el-button type="primary" @click="queryCompanyStats" class="query-button" :loading="loading">
                <el-icon><Search /></el-icon> 查询统计
              </el-button>
            </div>
          </div>
        </template>
        <!-- 产品上下游关系查询 -->
        <template v-else-if="activeTab === 'productChain'">
          <el-form :model="productChainForm" label-position="top" @submit.prevent="queryProductChain">
            <el-form-item label="产品名称" required>
              <el-autocomplete
                v-model="productChainForm.productName"
                :fetch-suggestions="queryProducts"
                placeholder="请输入产品名称"
                clearable
                class="form-input"
                value-key="name"
                @select="(item) => productChainForm.selectedProduct = item"
                :trigger-on-focus="true"
                :highlight-first-item="true"
              >
                <template #default="{ item }">
                  <div class="product-item">
                    <div>{{ item.name }}</div>
                    <div class="product-description" v-if="item.description">{{ item.description }}</div>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="查询深度">
              <el-slider
                v-model="productChainForm.depth"
                :min="1"
                :max="5"
                :step="1"
                :marks="{1:'1', 2:'2', 3:'3', 4:'4', 5:'5'}"
                show-stops
                class="form-slider"
              />
            </el-form-item>
            <el-form-item label="关系方向" class="direction-selector">
              <el-radio-group v-model="productChainForm.direction" size="large" class="direction-radio-group">
                <el-radio label="both">上下游</el-radio>
                <el-radio label="upstream">上游</el-radio>
                <el-radio label="downstream">下游</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="text-align: center; margin-top: 20px;">
              <el-button type="primary" @click="queryProductChain" class="query-button">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button type="success" @click="identifyKeyMaterials" class="key-materials-button">
              <el-icon><Goods /></el-icon> 关键材料识别
            </el-button>
            <el-button @click="resetProductChainForm" class="reset-button">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-card>
      <!-- 右侧结果展示 -->
      <el-card class="graph-card" shadow="hover" v-loading="loading">
        <div class="graph-header">
          <h3>{{ getResultTitle(activeTab) }}</h3>
          <div class="graph-controls">
            <el-button-group>
              <el-button @click="exportData" type="primary" plain class="control-button">
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
              <el-button @click="toggleFullscreen" type="primary" plain class="control-button">
                <el-icon><FullScreen v-if="!isFullscreen" /><Close v-else /></el-icon>
                {{ isFullscreen ? '退出全屏' : '全屏' }}
              </el-button>
            </el-button-group>
          </div>
        </div>
        <!-- 统计信息展示区域 -->
        <div v-if="industryStats" class="stats-overview" :data-tab="activeTab">
          <el-row :gutter="20">
            <!-- 行业风险统计 -->
            <template v-if="activeTab === 'companyRisks'">
              <el-col :span="8">
                <el-statistic title="行业名称" :value="industryStats.industry" class="statistic-item" />
              </el-col>
              <el-col :span="8">
                <el-statistic title="风险阈值" :value="riskForm.minRiskCount" class="statistic-item" />
              </el-col>
              <el-col :span="8">
                <el-statistic title="风险企业数量" :value="industryStats.riskyCompanyCount" class="statistic-item" />
              </el-col>
              <!-- 以下内容只在非企业风险分析时才显示，防止冗余显示 -->
              <template v-if="false">
                <el-col :span="6">
                  <el-statistic 
                    title="高新技术企业数量" 
                    :value="industryStats.highTechCount" 
                    class="statistic-item"
                  />
                </el-col>
                <el-col :span="6">
                  <el-statistic 
                    title="平均注册资本" 
                    :value="industryStats.avgRegisteredCapital ? industryStats.avgRegisteredCapital.toFixed(2) : '0.00'" 
                    suffix="万元" 
                    class="statistic-item"
                  />
                </el-col>
              </template>
            </template>
            <!-- 行业统计 -->
            <template v-if="activeTab === 'industryComprehensive'">
              <el-col :span="6">
                <el-statistic title="企业数量" :value="industryStats.companyCount" class="statistic-item" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="员工总数" :value="industryStats.totalEmployees" class="statistic-item" />
              </el-col>
              <el-col :span="6">
                <el-statistic 
                  title="平均注册资本" 
                  :value="industryStats.avgCapital ? industryStats.avgCapital.toFixed(2) : '0.00'" 
                  suffix="万元" 
                  class="statistic-item"
                />
              </el-col>
              <el-col :span="6">
                <el-statistic 
                  title="高新技术企业数量" 
                  :value="industryStats.highTechCount" 
                  class="statistic-item"
                />
              </el-col>
            </template>
            <!-- 高新技术企业统计 -->
            <template v-else-if="activeTab === 'regionStats'">
              <el-col :span="8">
                <el-statistic title="统计省份数量" :value="statsData ? statsData.length : 0" class="statistic-item" />
              </el-col>
              <el-col :span="8">
                <el-statistic 
                  title="企业总数" 
                  :value="statsData ? statsData.reduce((sum, item) => sum + item.companyCount, 0) : 0" 
                  class="statistic-item" 
                />
              </el-col>
              <el-col :span="8">
                <el-statistic 
                  title="高新企业总数" 
                  :value="statsData ? statsData.reduce((sum, item) => sum + item.highTechCount, 0) : 0" 
                  class="statistic-item"
                />
              </el-col>
            </template>
          </el-row>
        </div>
        <!-- 图表或表格区域 -->
        <div v-if="showGraph" class="graph-content">
          <div v-if="graphData && graphData.nodes && graphData.nodes.length > 0" class="graph-inner">
            <div class="graph-container" ref="graphContainer"></div>
            <!-- 修复按钮 -->
            <el-button v-if="!isFullscreen" type="warning" style="margin-top: 10px;" @click="window.location.reload()">刷新页面修复图表</el-button>
            <!-- 备用图表容器 -->
            <div v-if="!isFullscreen" id="backupChartContainer" style="width: 100%; height: 600px; border: 1px solid #ddd; margin-top: 20px;"></div>
          </div>
          <div v-else-if="activeTab === 'regionStats' && statsData && statsData.length > 0" class="stats-container">
            <div class="chart-container" ref="companyCountChart"></div>
            <div class="chart-container" ref="employeeCountChart"></div>
            <div class="chart-container" ref="capitalChart"></div>
            <div class="chart-container" ref="highTechChart"></div>
          </div>
          <div v-else-if="activeTab === 'regionStats' && loading" class="loading-container">
            <el-skeleton style="width: 100%" animated>
              <template #template>
                <el-skeleton-item variant="rect" style="width: 100%; height: 550px;" />
              </template>
            </el-skeleton>
          </div>
          <div v-else-if="activeTab === 'regionStats'" class="empty-stats">
            <el-empty description="暂无区域企业统计数据"></el-empty>
          </div>
          <div v-else-if="activeTab === 'industryComprehensive' && comprehensiveData" class="comprehensive-analysis">
            <!-- 基础信息统计卡片 -->
            <el-row :gutter="20" class="stat-cards">
              <el-col :span="24">
                <el-card shadow="hover" class="stat-card" :class="{'risk-stat-hidden': activeTab === 'companyRisks'}">
                  <h3 class="stat-title">行业基本情况</h3>
                  <el-row :gutter="20">
                    <el-col :span="6">
                      <el-statistic title="企业总数" :value="comprehensiveData.industryStatistics.companyCount || 0" />
                    </el-col>
                    <el-col :span="6">
                      <el-statistic title="总员工数" :value="comprehensiveData.industryStatistics.totalEmployees || 0" />
                    </el-col>
                    <el-col :span="6">
                      <el-statistic title="平均注册资本" :value="comprehensiveData.industryStatistics.avgCapital || 0" :precision="2">
                        <template #suffix>
                          <span>万元</span>
                        </template>
                      </el-statistic>
                    </el-col>
                    <el-col :span="6">
                      <el-statistic title="高新技术企业占比" :value="(comprehensiveData.industryStatistics.hightechRatio || 0) * 100" :precision="1">
                        <template #suffix>
                          <span>%</span>
                        </template>
                      </el-statistic>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 图表区域 -->
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="12">
                <el-card shadow="hover" class="chart-card" :class="{'risk-stat-hidden': activeTab === 'companyRisks'}">
                  <h3 class="stat-title">企业规模分布</h3>
                  <div id="companySizeChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card shadow="hover" class="chart-card" :class="{'risk-stat-hidden': activeTab === 'companyRisks'}">
                  <h3 class="stat-title">高新企业与普通企业对比</h3>
                  <div id="comparisonChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 专利分布和创新效率 -->
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="12">
                <el-card shadow="hover" class="chart-card" :class="{'risk-stat-hidden': activeTab === 'companyRisks'}">
                  <h3 class="stat-title">专利分布TOP10</h3>
                  <div id="patentDistributionChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card shadow="hover" class="chart-card" :class="{'risk-stat-hidden': activeTab === 'companyRisks'}">
                  <h3 class="stat-title">创新效率TOP10</h3>
                  <div id="innovationEfficiencyChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { ref, reactive, onMounted, nextTick, computed, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
// eslint-disable-next-line no-unused-vars
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import { 
  Connection, 
  OfficeBuilding, 
  Warning, 
  DataAnalysis, 
  PieChart, 
  Download, 
  FullScreen, 
  Close,
  Goods,
  Search,
  Refresh,
  Link,
  TrendCharts,
  DataBoard
} from '@element-plus/icons-vue';
import {
  getSupplyChain,
  getIndustryCompanies,
  getCompanyRisks,
  getHighTechCompanies,
  getCompanyStats,
  getProductChain,
  getSupplyChainPath,
  searchProducts, // 添加searchProducts以便直接使用
  getIndustryAnalysis, // 添加行业分析API
  getIndustryComprehensiveAnalysis, getKeyMaterials // 添加行业企业综合分析API
} from '@/api/graphAnalysis';
import { searchCompanies } from '@/api/company';
import { hasPermission, hasGraphPermission } from '@/utils/permission';
export default {
  name: 'GraphAnalysis',
  components: {
    Warning,
    Download,
    FullScreen,
    Close,
    Goods,
    Search,
    Refresh,
    Link,
    TrendCharts,
    DataBoard
  },
  setup() {
    // 移除未使用的store引用
    const router = useRouter();
    
    // 各功能模块的权限状态
    const permissionStatus = computed(() => {
      return {
        base: hasPermission('graph:view'),
        supplyChain: hasPermission('analysis:supply-chain'),
        industryChain: hasPermission('analysis:industry-chain'),
        companyRisk: hasPermission('analysis:company-risk'),
        highTech: hasPermission('analysis:high-tech'),
        productChain: hasPermission('analysis:product-chain'),
        companyStats: hasPermission('analysis:company-stats')
      };
    });
    
    // 检查基础权限
    if (!hasPermission('graph:view') && !hasGraphPermission()) {
      ElMessage.error('您没有知识图谱分析的权限，请联系管理员授权');
      router.push('/dashboard');
    }
    
    // 状态变量 - 根据权限设置默认查询类型
    const getDefaultQueryType = () => {
      const permissions = [
        { perm: 'analysis:supply-chain', type: 'supplyChain' },
        { perm: 'analysis:industry-chain', type: 'industry' },
        { perm: 'analysis:company-risk', type: 'companyRisks' },
        { perm: 'analysis:high-tech', type: 'regionStats' },
        { perm: 'analysis:product-chain', type: 'productChain' },
        { perm: 'analysis:company-stats', type: 'regionStats' }
      ];
      
      // 找到用户有权限的第一个查询类型
      const firstAvailable = permissions.find(p => hasPermission(p.perm));
      return firstAvailable ? firstAvailable.type : 'supplyChain';
    };
    
    const activeTab = ref(getDefaultQueryType());
    const loading = ref(false);
    const graphData = ref({ nodes: [], relationships: [] });
    const statsData = ref(null);
    const graphContainer = ref(null);
    const companyCountChart = ref(null);
    const employeeCountChart = ref(null);
    const capitalChart = ref(null);
    const highTechChart = ref(null);
    let graphChart = null;
    const isFullscreen = ref(false);
    const industryStats = ref(null);
    const showGraph = ref(false);
    const comprehensiveData = ref(null);
    // 表单数据
    const supplyChainForm = reactive({
      companyName: '',
      depth: 2
    });
    const industryForm = reactive({
      industryName: ''
    });
    const riskForm = reactive({
      industryName: '',
      minRiskCount: 10
    });
    const highTechForm = reactive({
      industryName: ''
    });
    const supplyPathForm = reactive({
      sourceCompany: '',
      targetCompany: '',
      maxDepth: 3
    });
    // 产品链技术决策支持系统表单
    const productChainForm = reactive({
      productName: '',
      selectedProduct: null,
      depth: 2,
      direction: 'both'
    });
    const industryComprehensiveForm = reactive({
      industryName: ''
    });
    // 重置产品链技术决策支持系统表单
    const resetProductChainForm = () => {
      productChainForm.productName = '';
      productChainForm.depth = 2;
      productChainForm.direction = 'both';
      productChainForm.selectedProduct = null;
    };
    // 行业选项
    const industryOptions = ref([
      { value: '黑色金属冶炼和压延加工业', label: '黑色金属冶炼和压延加工业' },
      { value: '有色金属冶炼和压延加工业', label: '有色金属冶炼和压延加工业' },
      { value: '电气机械和器材制造业', label: '电气机械和器材制造业' },
      { value: '计算机、通信和其他电子设备制造业', label: '计算机、通信和其他电子设备制造业' },
      { value: '汽车制造业', label: '汽车制造业' }
    ]);
    // 查询公司名称建议
    const queryCompanies = async (queryString, callback) => {
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await searchCompanies({ keyword: queryString })
        // 增加空数据校验
        const data = response?.data || []
        if (!Array.isArray(data)) {
          throw new Error('无效的响应结构')
        }
        
        const results = data.map(item => ({
          value: item.name,
          id: String(item.id),
          _raw: item
        }))
        
        callback(results)
      } catch (error) {
        console.error('搜索失败:', error)
        // 增加空数组返回防止UI报错
        callback([])
      }
    };
    // 查询产品名称建议
    const queryProducts = async (queryString, callback) => {
      if (queryString.trim() === '') {
        // 如果查询字符串为空，尝试获取所有产品
        try {
        // 设置显示图表
        showGraph.value = true;

                  console.log('查询所有产品');
          const response = await searchProducts({ keyword: '' });
          console.log('查询所有产品响应:', response);
          
          // 检查响应结构
          if (response && Array.isArray(response)) {
            // 直接是数组的情况
            const suggestions = response.map(item => ({
              value: item.name,
              name: item.name,
              description: item.description || '',
              ...item
            }));
            callback(suggestions);
          } else if (response && response.data && Array.isArray(response.data)) {
            // 包含data字段的情况
            const suggestions = response.data.map(item => ({
              value: item.name,
              name: item.name,
              description: item.description || '',
              ...item
            }));
            callback(suggestions);
          } else if (response && Array.isArray(response.records)) {
            // 包含records字段的情况
            const suggestions = response.records.map(item => ({
              value: item.name,
              name: item.name,
              description: item.description || '',
              ...item
            }));
            callback(suggestions);
          } else {
            console.warn('查询所有产品返回结构不符合预期:', response);
            callback([]);
          }
        } catch (error) {
          console.error('查询所有产品失败:', error);
          callback([]);
        }
        return;
      }
      
      try {
        // 设置显示图表
        showGraph.value = true;

                console.log('查询产品:', queryString);
        const response = await searchProducts({ keyword: queryString });
        console.log('查询产品响应:', response);
        
        // 检查响应结构
        if (response && Array.isArray(response)) {
          // 直接是数组的情况
          const suggestions = response.map(item => ({
            value: item.name,
            name: item.name,
            description: item.description || '',
            ...item
          }));
          callback(suggestions);
        } else if (response && response.data && Array.isArray(response.data)) {
          // 包含data字段的情况
          const suggestions = response.data.map(item => ({
            value: item.name,
            name: item.name,
            description: item.description || '',
            ...item
          }));
          callback(suggestions);
        } else if (response && Array.isArray(response.records)) {
          // 包含records字段的情况
          const suggestions = response.records.map(item => ({
            value: item.name,
            name: item.name,
            description: item.description || '',
            ...item
          }));
          callback(suggestions);
        } else {
          console.warn('查询产品返回结构不符合预期:', response);
          callback([]);
        }
      } catch (error) {
        console.error('查询产品失败:', error);
        callback([]);
      }
    };
    // 添加行业名称搜索建议函数
    const queryIndustrySearch = (queryString, callback) => {
      const results = industryOptions.value
        .filter(item => item.label.toLowerCase().includes(queryString.toLowerCase()))
        .map(item => ({ value: item.label }));
      callback(results);
    };
    // 处理风险模块行业选择
    const handleRiskIndustrySelect = (item) => {
      riskForm.industryName = item.value;
    };
    // 查询处理函数
    const handleQueryChange = (queryType) => {
      // 更新当前查询类型
      activeTab.value = queryType;
      
      // 清理图表实例
      if (graphChart) {
        graphChart.dispose();
        graphChart = null;
      }
      
      // 清理统计图表
      if (window.statsChartCleanup) {
        window.statsChartCleanup();
        window.statsChartCleanup = null;
      }
      
      graphData.value = { nodes: [], relationships: [] };
      statsData.value = [];
      industryStats.value = null; // 清除行业统计数据
      
      // 如果选择了产品上下游关系且已有产品名称，自动调用查询接口
      if (queryType === 'productChain' && productChainForm.productName) {
        console.log('自动查询产品上下游关系:', productChainForm.productName);
        queryProductChain();
      }
      
      // 不再自动触发其他查询
      // 用户需要点击查询按钮才会触发查询
    };
    // 获取查询标题
    const getQueryTitle = (queryType) => {
      const titles = {
        supplyChain: '产业链上下游分析',
        industryComprehensive: '行业企业综合分析',
        companyRisks: '企业风险分析',
        regionStats: '区域企业统计',
        supplyPath: '供应链路径查询',
        companyStats: '区域企业统计',
        productChain: '产品链技术决策支持'
      };
      return titles[queryType] || '知识图谱分析';
    };
    // 获取结果标题
    const getResultTitle = (queryType) => {
      const titles = {
        supplyChain: '产业链关系图',
        industryComprehensive: '行业企业关系图',
        companyRisks: '企业风险关系图',
        regionStats: '区域企业统计图表',
        supplyPath: '供应链路径图',
        companyStats: '区域企业统计图表',
        productChain: '产品链技术决策支持'
      };
      return titles[queryType] || '分析结果';
    };
    // 统一查询处理
    const handleQuery = async () => {
      if (loading.value) return;
      
      loading.value = true;
      graphData.value = { nodes: [], relationships: [] };
      statsData.value = null;
      showGraph.value = false; // 重置显示状态
      
      try {
        // 设置显示图表
        showGraph.value = true;

                // 产业链上下游分析
        if (activeTab.value === 'supplyChain') {
          await querySupplyChain();
        }
        // 行业内企业分析
        else if (activeTab.value === 'industry') {
          await queryIndustry();
        }
        // 企业风险分析
        else if (activeTab.value === 'companyRisks') {
          await queryCompanyRisks();
        }
        // 高新技术企业分析
        else if (activeTab.value === 'regionStats') {
          await queryCompanyStats();
        }
        // 供应链路径分析
        else if (activeTab.value === 'supplyPath') {
          await querySupplyPath();
        }
        // 区域企业统计
        else if (activeTab.value === 'companyStats') {
          await queryCompanyStats();
        }
        // 产品上下游关系
        else if (activeTab.value === 'productChain') {
          await queryProductChain();
        }
        // 行业企业综合分析
        else if (activeTab.value === 'industryComprehensive') {
          await queryIndustryComprehensive();
        }
        
        // 在查询结束后不再设置showGraph，让各查询函数自己决定显示时机
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败，请稍后重试');
        showGraph.value = false;
      } finally {
        loading.value = false;
      }
    };
    // 产业链上下游分析
    const querySupplyChain = async () => {
      if (!permissionStatus.value.supplyChain) {
        ElMessage.error('您没有供应链分析权限，请联系管理员授权');
        return;
      }
      
      let timeoutId;
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await getSupplyChain({
          companyName: supplyChainForm.companyName.trim(),
          depth: supplyChainForm.depth
        }, { 
          validateStatus: (status) => status < 500 // 允许400状态码不触发reject
        });
        // 数据校验和转换
        graphData.value = {
          nodes: response.nodes.map(n => ({
            id: String(n.id),
            name: n.name,
            symbolSize: 50,
            value: {
              employeeCount: n.employeeCount,
              companyScale: n.companyScale,
              registeredCapital: n.registeredCapital,
              establishYear: n.establishYear,
              province: n.province,
              riskCount: n.riskCount,
              isHighTech: n.isHighTech
            },
            // 保留这些属性以兼容旧代码
            employeeCount: n.employeeCount,
            companyScale: n.companyScale,
            registeredCapital: n.registeredCapital,
            establishYear: n.establishYear,
            province: n.province,
            riskCount: n.riskCount,
            isHighTech: n.isHighTech,
            category: n.isHighTech ? 0 : 1
          })),
          relationships: response.links.map(r => ({
            source: String(r.source),
            target: String(r.target),
            type: r.type || 'SUPPLIES',
            value: r.type || '供应关系'
          }))
        };
        console.log(graphData.value);
        console.log('原始关系数据:', response.links);
        console.log('处理后的关系数据:', graphData.value.relationships);
        // 添加空数据校验
        if (graphData.value.nodes.length === 0) {
          ElMessage.warning('未找到相关供应链数据');
          return;
        }
        console.log("renderGraph");
        // 使用nextTick确保DOM更新
        nextTick(() => {
          renderGraph();
          });
        } catch (error) {
        clearTimeout(timeoutId);
        // 细化错误分类处理
        if (error.name === 'AbortError') {
          ElMessage.error('请求超时，请稍后重试');
        } else if (error.response?.status === 404) {
          ElMessage.warning('未找到相关企业信息');
        } else {
          console.error('完整错误上下文:', {
            error,
            requestParams: {
              companyName: supplyChainForm.companyName,
              depth: supplyChainForm.depth
            },
            timestamp: new Date().toISOString()
          });
          ElMessage.error(`系统繁忙，错误代码：${error.code || 'UNKNOWN'}`);
        }
      }
    };
    // 行业内企业分析
    const queryIndustry = async () => {
      if (!industryForm.industryName) {
        ElMessage.warning('请选择行业名称');
        return;
      }
      loading.value = true;
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await getIndustryCompanies({
          industryName: industryForm.industryName
        });
        
        // 处理行业内企业数据
        if (response && response.companies && response.companies.length > 0) {
          // 提取行业名称
          const industryName = industryForm.industryName;
          
          // 计算统计数据
          const companyCount = response.companies.length;
          const totalEmployees = response.companies.reduce((sum, company) => 
            sum + (company.employeeCount || 0), 0);
          const totalCapital = response.companies.reduce((sum, company) => 
            sum + (company.registeredCapital || 0), 0);
          const avgEmployees = companyCount > 0 ? totalEmployees / companyCount : 0;
          const avgCapital = companyCount > 0 ? totalCapital / companyCount : 0;
          
          // 计算企业规模种类数量
          const scaleTypes = new Set();
          response.companies.forEach(company => {
            if (company.companyScale) scaleTypes.add(company.companyScale);
          });
          const scaleCount = scaleTypes.size;
          
          // 计算风险总数
          const totalRiskCount = response.companies.reduce((sum, company) => 
            sum + (company.riskCount || 0), 0);
          
          // 计算高新技术企业数量
          const highTechCount = response.companies.filter(company => 
            company.isHighTech).length;
          
          // 将企业数据转换为图谱节点
          graphData.value = {
            nodes: response.companies.map(company => ({
              id: company.id || company.name,
              name: company.name,
              symbolSize: 50,
              value: {
                employeeCount: company.employeeCount,
                companyScale: company.companyScale,
                registeredCapital: company.registeredCapital,
                establishYear: company.establishYear,
                province: company.province,
                riskCount: company.riskCount,
                isHighTech: company.isHighTech
              },
              // 保留这些属性以兼容旧代码
              employeeCount: company.employeeCount,
              companyScale: company.companyScale,
              registeredCapital: company.registeredCapital,
              establishYear: company.establishYear,
              province: company.province,
              riskCount: company.riskCount,
              isHighTech: company.isHighTech,
              category: company.isHighTech ? 0 : 1
            })),
            relationships: [] // 行业内企业暂不显示关系
          };
          
          // 更新页面上的统计信息展示
          industryStats.value = {
            industry: industryName,
            companyCount: companyCount,
            totalEmployees: totalEmployees,
            avgCapital: avgCapital,
            avgEmployees: avgEmployees,
            scaleCount: scaleCount,
            totalRiskCount: totalRiskCount,
            highTechCount: highTechCount
          };
          
          // 确保渲染图表
          nextTick(() => {
            renderGraph();
          });
        } 
        // 处理直接返回统计数据的情况
        else if (response && response.industry) {
          console.log('接收到行业统计数据:', response);
          
          // 直接使用后端返回的统计数据
          industryStats.value = {
            industry: response.industry,
            companyCount: response.companyCount || 0,
            totalEmployees: response.totalEmployees || 0,
            avgCapital: response.avgCapital || 0,
            avgEmployees: response.avgEmployees || 0,
            scaleCount: response.scaleCount || 0,
            totalRiskCount: response.totalRiskCount || 0,
            highTechCount: response.highTechCount || 0
          };
          
          // 创建一个表示行业的节点
          graphData.value = {
            nodes: [
              {
                id: 'industry',
                name: response.industry,
                symbolSize: 50,
                value: {
                  companyCount: response.companyCount || 0,
                  totalEmployees: response.totalEmployees || 0,
                  avgCapital: response.avgCapital || 0,
                  avgEmployees: response.avgEmployees || 0,
                  scaleCount: response.scaleCount || 0,
                  totalRiskCount: response.totalRiskCount || 0,
                  highTechCount: response.highTechCount || 0
                },
                // 保留type属性以便在renderGraph中区分不同类型的节点
                type: 'industry',
                // 保留properties属性以兼容旧代码
                properties: {
                  companyCount: response.companyCount || 0,
                  totalEmployees: response.totalEmployees || 0,
                  avgCapital: response.avgCapital || 0,
                  avgEmployees: response.avgEmployees || 0,
                  scaleCount: response.scaleCount || 0,
                  totalRiskCount: response.totalRiskCount || 0,
                  highTechCount: response.highTechCount || 0
                }
              }
            ],
            relationships: []
          };
          
          // 确保渲染图表
          nextTick(() => {
            renderGraph();
          });
        } else {
          console.warn('无效的行业数据:', response);
          industryStats.value = null;
          graphData.value = {
            nodes: [],
            relationships: []
          };
          ElMessage.warning('未找到相关行业数据');
        }
      } catch (error) {
        console.error('获取行业数据失败:', error);
        industryStats.value = null;
        graphData.value = {
          nodes: [],
          relationships: []
        };
        ElMessage.error('获取行业数据失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };
    // 企业风险分析
    const queryCompanyRisks = async () => {
      if (!riskForm.industryName) {
        ElMessage.warning('请选择行业名称');
        return;
      }
      loading.value = true;
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await getCompanyRisks({
          industryName: riskForm.industryName,
          minRiskCount: riskForm.minRiskCount
        });
        
        // 修改数据检查逻辑
        if (response && response.riskyCompanies && response.riskyCompanies.length > 0) {
          // 将风险企业数据转换为图谱需要的格式
          graphData.value = {
            nodes: response.riskyCompanies.map(company => ({
              id: company.company,
              name: company.company,
              symbolSize: 50,
              value: {
                riskCount: company.riskCount,
                riskTypes: company.riskTypes,
                employeeCount: company.employeeCount,
                companyScale: company.companyScale,
                registeredCapital: company.registeredCapital,
                establishYear: company.establishYear,
                province: company.province,
                isHighTech: company.isHighTech
              },
              // 保留这些属性以兼容旧代码
              riskCount: company.riskCount,
              riskTypes: company.riskTypes,
              employeeCount: company.employeeCount,
              companyScale: company.companyScale,
              registeredCapital: company.registeredCapital,
              establishYear: company.establishYear,
              province: company.province,
              isHighTech: company.isHighTech,
              category: company.isHighTech ? 0 : 1
            })),
            relationships: [] // 风险分析暂时不需要关系数据
          };
          
          // 只保留风险分析相关的统计数据，移除高新企业相关的统计
          industryStats.value = {
            industry: response.industry,
            minRiskThreshold: response.minRiskCount,
            riskyCompanyCount: response.riskyCompanies.length,
            // 移除下面可能导致冗余显示的统计信息
            highTechCount: null,
            avgRegisteredCapital: null,
            totalEmployees: null
          };
          
          // 确保显示图表
          showGraph.value = true;
        } else {
          graphData.value = {
            nodes: [],
            relationships: []
          };
          ElMessage.warning('未找到相关风险企业数据');
        }
        
        nextTick(() => {
          renderGraph();
        });
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败，请稍后重试');
        graphData.value = {
          nodes: [],
          relationships: []
        };
      } finally {
        loading.value = false;
      }
    };
    // 高新技术企业分析
    const queryHighTechCompanies = async () => {
      if (!highTechForm.industryName) {
        ElMessage.warning('请选择行业名称');
        return;
      }
      loading.value = true;
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await getHighTechCompanies({
          industryName: highTechForm.industryName
        });
        
        console.log('高新技术企业数据:', response);
        
        // 检查返回的数据格式
        if (response.data && (response.data.nodes || response.data.relationships)) {
          // 如果返回的是图表数据格式，直接使用
          graphData.value = response.data;
        } else if (response.industry || response.highTechCount) {
          // 如果返回的是统计数据，创建一个节点来表示行业高新技术企业统计
          const industryName = response.industry || highTechForm.industryName;
          const highTechCount = response.highTechCount || 0;
          const avgRegisteredCapital = response.avgRegisteredCapital || 0;
          const totalEmployees = response.totalEmployees || 0;
          
          // 创建一个表示行业的节点
          graphData.value = {
            nodes: [
              {
                id: 'hightech-industry',
                name: `${industryName} 高新技术企业`,
                value: highTechCount,
                type: 'hightech-industry',
                properties: {
                  industry: industryName,
                  highTechCount: highTechCount,
                  avgRegisteredCapital: avgRegisteredCapital,
                  totalEmployees: totalEmployees
                }
              }
            ],
            relationships: []
          };
          
          // 更新行业统计信息
          industryStats.value = {
            industry: industryName,
            highTechCount: highTechCount,
            avgRegisteredCapital: avgRegisteredCapital,
            totalEmployees: totalEmployees
          };
        } else {
          // 如果数据格式不符合预期，显示警告
          ElMessage.warning('未找到高新技术企业数据');
          graphData.value = { nodes: [], relationships: [] };
        }
        
        nextTick(() => {
          renderGraph();
        });
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败，请稍后重试');
        graphData.value = { nodes: [], relationships: [] };
      } finally {
        loading.value = false;
      }
    };
    // 供应链路径查询
    const querySupplyPath = async () => {
      if (!supplyPathForm.sourceCompany || !supplyPathForm.targetCompany) {
        ElMessage.warning('请输入源公司和目标公司名称');
        return;
      }
      loading.value = true;
      try {
        // 设置显示图表
        showGraph.value = true;

                const response = await getSupplyChainPath({
          sourceCompany: supplyPathForm.sourceCompany,
          targetCompany: supplyPathForm.targetCompany,
          maxDepth: supplyPathForm.maxDepth
        });
        
        console.log('供应链路径查询结果:', response);
        
        // 检查返回的数据格式并处理
        if (response && response.nodes && response.nodes.length > 0) {
          // 处理节点数据，确保数据结构一致
          const processedNodes = response.nodes.map(node => ({
            id: String(node.id || node.name),
            name: node.name,
            symbolSize: 50,
            value: {
              employeeCount: node.properties?.employee_count,
              companyScale: node.properties?.company_scale,
              registeredCapital: node.properties?.registered_capital,
              establishYear: node.properties?.establish_year,
              province: node.properties?.province,
              riskCount: node.properties?.risk_count,
              isHighTech: node.properties?.is_high_tech
            },
            // 保留这些属性以兼容旧代码
            employeeCount: node.properties?.employee_count,
            companyScale: node.properties?.company_scale,
            registeredCapital: node.properties?.registered_capital,
            establishYear: node.properties?.establish_year,
            province: node.properties?.province,
            riskCount: node.properties?.risk_count,
            isHighTech: node.properties?.is_high_tech,
            category: node.properties?.is_high_tech ? 0 : 1
          }));
          
          // 处理关系数据
          const processedRelationships = response.relationships.map(rel => ({
            source: String(rel.source),
            target: String(rel.target),
            type: rel.type || 'SUPPLIES',
            // 添加关系标签
            name: rel.type || 'SUPPLIES',
            value: rel.type || '供应关系'
          }));
          
          graphData.value = {
            nodes: processedNodes,
            relationships: processedRelationships
          };
          
          nextTick(() => {
            renderGraph();
          });
        } else {
          // 如果数据格式不符合预期，显示警告
          ElMessage.warning('未找到相关供应链路径数据');
          graphData.value = { nodes: [], relationships: [] };
        }
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败，请稍后重试');
        graphData.value = { nodes: [], relationships: [] };
      } finally {
        loading.value = false;
      }
    };
    // 区域企业统计
    const queryCompanyStats = async () => {
      if (!permissionStatus.value.companyStats) {
        ElMessage.error('您没有企业统计分析权限，请联系管理员授权');
        return;
      }
      
      loading.value = true;
      statsData.value = null; // 清空之前的数据
      
      try {
        // 设置显示图表
        showGraph.value = true;

        // 获取当前分析的行业名称
        let currentIndustryName = null;
        
        // 尝试从不同表单状态中获取行业名称
        if (activeTab.value === 'industryComprehensive' && industryComprehensiveForm.industryName) {
          currentIndustryName = industryComprehensiveForm.industryName;
        } else if (activeTab.value === 'industryChain' && industryForm.industryName) {
          currentIndustryName = industryForm.industryName;
        } else if (activeTab.value === 'companyRisks' && riskForm.industryName) {
          currentIndustryName = riskForm.industryName;
        } else if (activeTab.value === 'highTechCompanies' && highTechForm.industryName) {
          currentIndustryName = highTechForm.industryName;
        }
        
        // 创建请求参数对象
        const params = {};
        if (currentIndustryName) {
          params.industryName = currentIndustryName;
          console.log('区域企业统计使用行业名称:', currentIndustryName);
        }

        const response = await getCompanyStats(params);
        
        console.log('区域企业统计数据:', response);
        
        // 检查返回的数据格式
        if (response && Array.isArray(response) && response.length > 0) {
          // 处理科学计数法显示的大数字
          statsData.value = response.map(item => ({
            ...item,
            totalCapital: typeof item.totalCapital === 'number' ? 
              parseFloat(item.totalCapital.toFixed(2)) : item.totalCapital
          }));
          
          // 使用nextTick确保DOM已更新
          nextTick(() => {
            renderStatsCharts();
          });
        } else if (response.data && Array.isArray(response.data) && response.data.length > 0) {
          // 处理科学计数法显示的大数字
          statsData.value = response.data.map(item => ({
            ...item,
            totalCapital: typeof item.totalCapital === 'number' ? 
              parseFloat(item.totalCapital.toFixed(2)) : item.totalCapital
          }));
          
          nextTick(() => {
            renderStatsCharts();
          });
        } else {
          // 如果数据格式不符合预期，显示警告
          ElMessage.warning('未找到区域企业统计数据');
          statsData.value = [];
        }
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败: ' + (error.message || '请稍后重试'));
        statsData.value = [];
      } finally {
        loading.value = false;
      }
    };
    // 查询产品上下游关系
    const queryProductChain = async () => {
      if (!productChainForm.productName) {
        ElMessage.warning('请输入产品名称');
        return;
      }
      
      try {
        // 设置显示图表
        showGraph.value = true;

                loading.value = true;
        console.log('查询产品上下游关系:', productChainForm);
        
        // 构建查询参数
        const params = {
          productName: productChainForm.productName,
          depth: productChainForm.depth,
          direction: productChainForm.direction
        };
        
        console.log('发送查询参数:', params);
        
        const response = await getProductChain(params);
        
        console.log('产品上下游关系查询结果:', response);
        
        // 检查响应结构
        if (response && response.data) {
          // 标准响应结构
          graphData.value = response.data;
        } else if (response && response.nodes) {
          // 直接返回图数据的结构
          graphData.value = response;
        } else if (response && typeof response === 'object') {
          // 其他可能的响应结构
          graphData.value = response;
        } else {
          console.warn('查询结果结构不符合预期:', response);
          graphData.value = { nodes: [], relationships: [] };
          loading.value = false; // 确保加载状态被重置
          return;
        }
        
        // 确保数据结构完整
        if (!graphData.value.nodes) graphData.value.nodes = [];
        if (!graphData.value.relationships) graphData.value.relationships = [];
        
        // 检查是否有节点数据
        if (graphData.value.nodes.length === 0) {
          ElMessage.warning('未找到相关产品关系数据');
          loading.value = false; // 确保加载状态被重置
          return;
        }
        
        // 渲染图表
        nextTick(() => {
          renderProductChainGraph();
        });
      } catch (error) {
        console.error('查询产品上下游关系失败:', error);
        ElMessage.error('查询失败: ' + (error.message || '未知错误'));
        graphData.value = { nodes: [], relationships: [] };
        loading.value = false; // 确保加载状态被重置
      }
    };
    // 渲染关系图
    const renderGraph = () => {
      console.log("调试:图表容器状态", graphContainer.value);
      if (!graphContainer.value) {
        console.error('图表容器元素不存在');
        return;
      }
      
      console.log('开始渲染图表...');
      
      // 如果图表实例已存在，先销毁
      if (graphChart) {
        graphChart.dispose();
      }
      
      // 创建新的图表实例
      graphChart = echarts.init(graphContainer.value);
      
      const nodes = graphData.value.nodes || [];
      const links = graphData.value.relationships || [];
      
      if (nodes.length === 0) {
        console.warn('没有节点数据，无法渲染图表');
        return;
      }
      
      console.log('节点数量:', nodes.length);
      console.log('关系数量:', links.length);
      
      // 设置节点颜色和大小
      const processedNodes = nodes.map(node => {
        // 确定节点类别
        let category = node.category || (node.isHighTech || node.value?.isHighTech ? 0 : 1);
        
        // 确定节点大小
        let symbolSize = 25; // 减小节点尺寸
        if (node.riskCount || node.value?.riskCount) {
          const riskCount = node.riskCount || node.value?.riskCount || 0;
          symbolSize = Math.max(25, Math.min(50, 25 + riskCount * 3)); // 调整风险节点范围
        }
        
        // 根据是否高新企业设置颜色
        const isHighTech = node.isHighTech === true || (node.value && node.value.isHighTech === true);
        const color = isHighTech ? '#409EFF' : '#67C23A'; // 高新企业蓝色，普通企业绿色
        
        // 返回处理后的节点数据
        return {
          ...node,
          name: node.name || '',
          value: node.value || {},
          category,
          symbolSize,
          itemStyle: {
            color: color
          },
          label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
            show: true,
            position: 'right',
            formatter: function(params) {
              // 如果名称过长，则截取
              const name = params.data.name;
              return name.length > 10 ? name.substring(0, 10) + '...' : name;
            }
          }
        };
      });
      
      // 处理关系数据
      const processedLinks = links.map(link => {
        return {
          ...link,
          value: link.value || '',
          lineStyle: {
            color: '#999',
            curveness: 0.1
          }
        };
      });
      
      // 图表配置
      const option = {
        title: {
          text: activeTab.value === 'companyRisks' ? '企业风险关系图' : '企业关系图谱',
          top: 'top',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.dataType === 'node') {
              const nodeData = params.data;
              
              // 根据当前查询类型定制提示内容
              if (activeTab.value === 'companyRisks') {
                // 企业风险查询的提示内容
                return `
                  <div style="font-weight:bold;margin-bottom:5px;">${nodeData.name || ''}</div>
                  <div>风险数量: ${nodeData.value?.riskCount || nodeData.riskCount || '未知'}</div>
                  <div>员工数量: ${nodeData.value?.employeeCount || nodeData.employeeCount || '未知'}</div>
                  <div>企业规模: ${nodeData.value?.companyScale || nodeData.companyScale || '未知'}</div>
                  <div>注册资本: ${nodeData.value?.registeredCapital || nodeData.registeredCapital || '未知'}万元</div>
                  <div>是否高新: ${(nodeData.value?.isHighTech || nodeData.isHighTech) ? '是' : '否'}</div>
                `;
              } else {
                // 其他查询的提示内容
                return `
                  <div style="font-weight:bold;margin-bottom:5px;">${nodeData.name || ''}</div>
                  <div>员工数量: ${nodeData.value?.employeeCount || nodeData.employeeCount || '未知'}</div>
                  <div>企业规模: ${nodeData.value?.companyScale || nodeData.companyScale || '未知'}</div>
                  <div>注册资本: ${nodeData.value?.registeredCapital || nodeData.registeredCapital || '未知'}万元</div>
                  <div>成立年份: ${nodeData.value?.establishYear || nodeData.establishYear || '未知'}</div>
                  <div>所在省份: ${nodeData.value?.province || nodeData.province || '未知'}</div>
                  <div>风险数量: ${nodeData.value?.riskCount || nodeData.riskCount || '未知'}</div>
                  <div>是否高新: ${(nodeData.value?.isHighTech || nodeData.isHighTech) ? '是' : '否'}</div>
                `;
              }
            } else {
              // 改进边的提示信息，显示关系方向
              const sourceNode = nodes.find(n => n.id === params.data.source);
              const targetNode = nodes.find(n => n.id === params.data.target);
              return `
                <div style="font-weight:bold;margin-bottom:5px;">关系类型: ${params.data.type || '供应关系'}</div>
                <div>${sourceNode?.name || params.data.source} → ${targetNode?.name || params.data.target}</div>
              `;
            }
          }
        },
        legend: {
          data: ['高新技术企业', '普通企业'],
          orient: 'vertical',
          left: 'left',
          textStyle: {
            rich: {
              highTech: {
                color: '#409EFF',
                fontWeight: 'bold'
              },
              normal: {
                color: '#67C23A',
                fontWeight: 'normal'
              }
            }
          },
          formatter: function(name) {
            if (name === '高新技术企业') {
              return '{highTech|' + name + '}';
            } else if (name === '普通企业') {
              return '{normal|' + name + '}';
            }
            return name;
          }
        },
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: '企业关系',
            type: 'graph',
            layout: 'force',
            data: processedNodes,
            links: processedLinks,
            categories: [
              { name: '高新技术企业' },
              { name: '普通企业' }
            ],
            roam: true,
            draggable: true,
            label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
              position: 'right',
              show: true,
              formatter: '{b}'
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 4
              }
            },
            force: {
              gravity: 0.1, // 添加重力参数
              friction: 0.6, // 添加摩擦力
              layoutAnimation: true, // 启用布局动画
              repulsion: 150,
              edgeLength: 80
            }
          }
        ]
      };
      
      // 在renderGraph函数中添加行业分析专用校验
      const industrySpecificCheck = activeTab.value === 'industryComprehensive' && 
        graphData.value.relationships.every(r => r.type === 'INDUSTRY_REL');
      if (industrySpecificCheck) {
        console.log('启用行业分析布局优化');
        option.series[0].layout = 'circular';
        option.series[0].force = {
          gravity: 0.2, // 增加重力参数
          friction: 0.8, // 增加摩擦力
          repulsion: 200,
          edgeLength: 80
        };
      }
      
      console.log('设置ECharts选项');
      graphChart.setOption(option, true);
      
      // 检查是否处于全屏状态，如果是则调整图表大小
      if (isFullscreen.value) {
        setTimeout(() => {
          graphChart.resize();
        }, 100);
      }
      
      console.log('图表渲染完成');
    };
    // 渲染统计图表
    const renderStatsCharts = () => {
      console.log('开始渲染统计图表...');
      console.log('统计数据:', statsData.value);
      
      // 创建图表实例数组，用于统一管理
      const chartInstances = [];
      
      // 企业数量统计图
      if (companyCountChart.value) {
        const chart = echarts.init(companyCountChart.value);
        chartInstances.push(chart);
        
        const provinces = statsData.value.map(item => item.province);
        const counts = statsData.value.map(item => item.companyCount);
        
        chart.setOption({
          title: {
            text: '各省企业数量统计',
            left: 'center',
            top: 5,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: provinces,
            axisLabel: {
              interval: 0,
              rotate: 45,
              fontSize: 9
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              fontSize: 9
            }
          },
          series: [
            {
              data: counts,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
              }
            }
          ]
        });
      } else {
        console.error('企业数量图表容器未找到');
      }
      
      // 员工数量统计图
      if (employeeCountChart.value) {
        const chart = echarts.init(employeeCountChart.value);
        chartInstances.push(chart);
        
        const provinces = statsData.value.map(item => item.province);
        const counts = statsData.value.map(item => item.totalEmployees);
        
        chart.setOption({
          title: {
            text: '各省员工数量统计',
            left: 'center',
            top: 5,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: provinces,
            axisLabel: {
              interval: 0,
              rotate: 45,
              fontSize: 9
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              fontSize: 9
            }
          },
          series: [
            {
              data: counts,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
              }
            }
          ]
        });
      } else {
        console.error('员工数量图表容器未找到');
      }
      
      // 注册资本统计图
      if (capitalChart.value) {
        const chart = echarts.init(capitalChart.value);
        chartInstances.push(chart);
        
        // 过滤掉null省份和注册资本为0的数据
        const filteredData = statsData.value
          .filter(item => item.province !== 'null' && item.province !== '未知' && item.totalCapital > 0)
          .map(item => ({
            name: item.province,
            value: item.totalCapital
          }));
        
        chart.setOption({
          title: {
            text: '各省注册资本统计(万元)',
            left: 'center',
            top: 5,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} 万元 ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'horizontal',
            bottom: 5,
            left: 'center',
            fontSize: 9,
            pageIconSize: 10,
            pageTextStyle: {
              fontSize: 9
            }
          },
          series: [
            {
              name: '注册资本',
              type: 'pie',
              radius: ['20%', '50%'],
              center: ['50%', '50%'],
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 2,
                borderColor: '#fff',
                borderWidth: 1
              },
              label: {
                fontSize: 10,
                distance: 5,
                show: true,
                formatter: '{b}\n{d}%',
                position: 'outside',
                distanceToLabelLine: 5
              },
              labelLine: {
                show: true,
                length: 8,
                length2: 4
              },
              data: filteredData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      } else {
        console.error('注册资本图表容器未找到');
      }
      
      // 高新企业统计图
      if (highTechChart.value) {
        const chart = echarts.init(highTechChart.value);
        chartInstances.push(chart);
        
        // 过滤掉高新企业数量为0的省份
        const filteredData = statsData.value
          .filter(item => item.province !== 'null' && item.province !== '未知' && item.highTechCount > 0);
        
        const provinces = filteredData.map(item => item.province);
        const counts = filteredData.map(item => item.highTechCount);
        
        chart.setOption({
          title: {
            text: '各省高新企业数量统计',
            left: 'center',
            top: 5,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: provinces,
            axisLabel: {
              interval: 0,
              rotate: 45,
              fontSize: 9
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              fontSize: 9
            }
          },
          series: [
            {
              data: counts,
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              lineStyle: {
                width: 2,
                color: '#5470C6'
              },
              itemStyle: {
                color: '#5470C6'
              }
            }
          ]
        });
      } else {
        console.error('高新企业图表容器未找到');
      }
      
      // 立即调整图表大小以适应容器
      setTimeout(() => {
        chartInstances.forEach(chart => {
          if (chart) {
            chart.resize();
          }
        });
      }, 0);
      
      // 添加窗口大小变化的监听器，确保图表能够自适应容器大小变化
      const resizeHandler = () => {
        chartInstances.forEach(chart => {
          if (chart) {
            chart.resize();
          }
        });
      };
      
      // 添加监听器
      window.addEventListener('resize', resizeHandler);
      
      // 初始调整大小
      setTimeout(() => {
        resizeHandler();
      }, 200);
      
      // 检查是否处于全屏状态，如果是则调整图表大小
      if (isFullscreen.value) {
        setTimeout(() => {
          resizeHandler();
        }, 300);
      }
      
      // 保存当前的图表实例和事件处理函数，以便在组件卸载时清理
      const cleanupFunction = () => {
        window.removeEventListener('resize', resizeHandler);
        chartInstances.forEach(chart => {
          if (chart) {
            chart.dispose();
          }
        });
      };
      
      // 将清理函数添加到全局变量，以便在组件卸载或切换查询类型时调用
      if (window.statsChartCleanup) {
        // 如果存在之前的清理函数，先调用它
        window.statsChartCleanup();
      }
      window.statsChartCleanup = cleanupFunction;
      
      console.log('统计图表渲染完成');
    };
    // 渲染产品链技术决策支持分析图
    const renderProductChainGraph = () => {
      try {
        // 设置显示图表
        showGraph.value = true;

                if (!graphData.value || !graphData.value.nodes || graphData.value.nodes.length === 0) {
          console.warn('产品关系图数据为空，无法渲染');
          loading.value = false; // 确保加载状态被重置
          return;
        }
        if (!graphContainer.value) {
          console.error('找不到图表容器');
          loading.value = false; // 确保加载状态被重置
          return;
        }
        // 如果已存在图表实例，先销毁
        if (graphChart) {
          graphChart.dispose();
        }
        // 初始化图表
        graphChart = echarts.init(graphContainer.value);
        
        console.log('产品关系图数据:', graphData.value);
        
        // 准备数据
        const nodes = graphData.value.nodes.map(node => {
          // 根据节点类型设置不同的样式
          let symbolSize = 25; // 减小节点尺寸
          let category = 0;
          
          if (node.type === 'Product') {
            symbolSize = 20; // 减小节点尺寸 // 减小节点尺寸
            category = 0;
          } else if (node.type === 'Material') {
            symbolSize = 25; // 减小节点尺寸
            category = 1;
          } else {
            symbolSize = 20; // 减小节点尺寸
            category = 2;
          }
          
          return {
            id: node.id,
            name: node.name,
            symbolSize: symbolSize,
            category: category,
            label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
              show: true
            },
            value: node.properties || {},
            description: node.description || '',
            type: node.type
          };
        });
        
        // 处理关系数据，正确解释UPSTREAM_OF关系
        const links = graphData.value.relationships.map(link => {
          // UPSTREAM_OF关系表示source是target的上游
          const relationshipType = link.type || '';
          let relationshipLabel = '';
          
          if (relationshipType === 'UPSTREAM_OF') {
            relationshipLabel = '上游';
          } else {
            relationshipLabel = relationshipType;
          }
          
          return {
            source: link.source,
            target: link.target,
            value: relationshipLabel,
            type: relationshipType
          };
        });
        
        // 图表配置
        const option = {
          title: {
            text: '产品链技术决策支持分析图',
            subtext: '数据来源: 知识图谱',
            top: 'top',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              if (params.dataType === 'node') {
                return `
                  <div style="font-weight:bold;margin-bottom:5px;">${params.data.name}</div>
                  <div>类型: ${params.data.type || '产品'}</div>
                  ${params.data.description ? `<div>描述: ${params.data.description}</div>` : ''}
                `;
              } else {
                // 显示关系方向
                const sourceNode = nodes.find(n => n.id === params.data.source);
                const targetNode = nodes.find(n => n.id === params.data.target);
                const sourceName = sourceNode ? sourceNode.name : params.data.source;
                const targetName = targetNode ? targetNode.name : params.data.target;
                
                if (params.data.type === 'UPSTREAM_OF') {
                  return `${sourceName} 是 ${targetName} 的上游`;
                } else {
                  return `${sourceName} → ${targetName}: ${params.data.value}`;
                }
              }
            }
          },
          legend: {
            data: ['产品', '原材料', '其他'],
            orient: 'vertical',
            left: 'left',
            top: 'middle'
          },
          series: [{
            type: 'graph',
            layout: 'force',
            data: nodes,
            links: links,
            categories: [
              { name: '产品' },
              { name: '原材料' },
              { name: '其他' }
            ],
            roam: true,
            label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
              show: true,
              position: 'right',
              formatter: '{b}'
            },
            force: {
              gravity: 0.1, // 添加重力参数
              friction: 0.6, // 添加摩擦力
              layoutAnimation: true, // 启用布局动画
              repulsion: 150,
              gravity: 0.1,
              edgeLength: [80, 120],
              layoutAnimation: true
            },
            lineStyle: {
              color: 'source',
              curveness: 0.3
            },
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [0, 10],
            edgeLabel: {
              show: true,
              formatter: '{c}',
              fontSize: 12
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 4
              }
            }
          }]
        };
        
        // 设置图表
        graphChart.setOption(option);
        
        // 监听窗口大小变化，调整图表大小
        const resizeHandler = () => {
          if (graphChart) {
            graphChart.resize();
          }
        };
        window.addEventListener('resize', resizeHandler);
        
        // 确保加载状态被重置
        loading.value = false;
        
        console.log('产品关系图渲染完成');
      } catch (error) {
        console.error('渲染产品关系图失败:', error);
        loading.value = false; // 确保加载状态被重置
        ElMessage.error('图表渲染失败: ' + (error.message || '未知错误'));
      }
    };
    const toggleFullscreen = () => {
      const graphCard = document.querySelector('.graph-card');
      if (!graphCard) {
        console.error('未找到图表容器元素');
        return;
      }
      
      if (!isFullscreen.value) {
        try {
          // 在进入全屏前强制设置整个页面背景
          document.documentElement.style.backgroundColor = 'white';
          document.body.style.backgroundColor = 'white';
          
          // 设置容器及其父容器背景色为白色
          graphCard.style.backgroundColor = 'white';
          graphCard.style.background = 'white';
          
          // 设置内部图表元素背景色
          graphCard.querySelectorAll('.graph-content, .graph-inner, .graph-container').forEach(el => {
            el.style.backgroundColor = 'white';
            el.style.background = 'white';
          });
          
          // 创建并应用全屏样式表
          const styleElement = document.createElement('style');
          styleElement.id = 'fullscreen-fix-style';
          styleElement.textContent = `
              :fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen {
                  background-color: white !important;
                  background: white !important;
              }
              ::backdrop, ::-webkit-backdrop {
                  background-color: white !important;
                  background: white !important;
              }
          `;
          document.head.appendChild(styleElement);
          
          if (graphCard.requestFullscreen) {
            graphCard.requestFullscreen();
          } else if (graphCard.mozRequestFullScreen) { // Firefox
            graphCard.mozRequestFullScreen();
          } else if (graphCard.webkitRequestFullscreen) { // Chrome, Safari and Opera
            graphCard.webkitRequestFullscreen();
          } else if (graphCard.msRequestFullscreen) { // IE/Edge
            graphCard.msRequestFullscreen();
          }
          isFullscreen.value = true;
        } catch (error) {
          console.error('进入全屏模式失败:', error);
        }
      } else {
        try {
          // 移除全屏样式表
          const styleElement = document.getElementById('fullscreen-fix-style');
          if (styleElement) {
              document.head.removeChild(styleElement);
          }
          
          // 添加安全检查 - 确保document仍然处于活动状态且有fullscreenElement
          if (!document.fullscreenElement && 
              !document.webkitFullscreenElement && 
              !document.mozFullScreenElement && 
              !document.msFullscreenElement) {
            console.log('当前没有元素处于全屏状态，直接更新状态');
            isFullscreen.value = false;
            return;
          }
          
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.mozCancelFullScreen) { // Firefox
            document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
            document.webkitExitFullscreen();
          } else if (document.msExitFullscreen) { // IE/Edge
            document.msExitFullscreen();
          }
          isFullscreen.value = false;
        } catch (error) {
          console.error('退出全屏模式失败:', error);
          // 如果退出全屏失败，强制更新状态
          isFullscreen.value = false;
        }
      }
      
      // 添加延时以确保全屏状态已经改变
      setTimeout(() => {
        if (graphChart) {
          graphChart.resize();
        }
      }, 300);
    };
    // 导出数据
    const exportData = () => {
      ElMessage.info('数据导出功能开发中...');
    };
    // 关键材料识别方法
    const identifyKeyMaterials = async () => {
      try {
        loading.value = true;
        console.log("开始识别关键材料节点...");
        
        const response = await getKeyMaterials();
        console.log("关键材料识别结果:", response);
        
        if (!response || (!response.nodes && !response.keyMaterialsByConnection)) {
          ElMessage.warning("未找到关键材料数据");
          loading.value = false;
          return;
        }
        
        // 更新图表数据
        graphData.value = {
          nodes: response.nodes || [],
          relationships: response.relationships || []
        };
        
        // 创建关键材料信息窗口
        const keyMaterialsByConnection = response.keyMaterialsByConnection || [];
        const keyMaterialsByIntermediary = response.keyMaterialsByIntermediary || [];
        
        // 创建关键材料信息标签
        let keyMaterialsInfo = "";
        
        if (keyMaterialsByConnection.length > 0) {
          keyMaterialsInfo += "<h3>按连接度排序的关键材料</h3><ul>";
          keyMaterialsByConnection.slice(0, 5).forEach(material => {
            keyMaterialsInfo += `<li>${material.name}: 连接度 ${material.connection_count}</li>`;
          });
          keyMaterialsInfo += "</ul>";
        }
        
        if (keyMaterialsByIntermediary.length > 0) {
          keyMaterialsInfo += "<h3>按中介中心性排序的关键材料</h3><ul>";
          keyMaterialsByIntermediary.slice(0, 5).forEach(material => {
            keyMaterialsInfo += `<li>${material.name}: 上游 ${material.upstream_count}, 下游 ${material.downstream_count}, 总连接 ${material.total_connections}</li>`;
          });
          keyMaterialsInfo += "</ul>";
        }
        
        // 显示关键材料信息
        ElMessageBox.alert(keyMaterialsInfo, "关键材料识别结果", {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定"
        });
        
        // 渲染关键材料网络图，首先修改graphData.value中的nodes数据
        if (graphData.value.nodes.length > 0 && keyMaterialsByConnection.length > 0) {
          const keyMaterialIds = new Set(keyMaterialsByConnection.map(m => m.id));
          
          graphData.value.nodes = graphData.value.nodes.map(node => {
            if (keyMaterialIds.has(node.id)) {
              // 这是关键材料节点，添加特殊标记
              return {
                ...node,
                isKeyMaterial: true,
                itemStyle: {
                  color: "#FF5722",  // 红色标记关键材料
                  borderColor: "#FFD700",
                  borderWidth: 2
                }
              };
            }
            return node;
          });
        }
        
        // 渲染网络图
        nextTick(() => {
          renderKeyMaterialsGraph();
        });
        
      } catch (error) {
        console.error("识别关键材料失败:", error);
        ElMessage.error("识别关键材料失败: " + (error.message || "未知错误"));
        loading.value = false;
      }
    };

    // 渲染关键材料网络图
    const renderKeyMaterialsGraph = () => {
      try {
        if (!graphData.value || !graphData.value.nodes || graphData.value.nodes.length === 0) {
          console.warn("关键材料图数据为空，无法渲染");
          loading.value = false;
          return;
        }
        
        if (!graphContainer.value) {
          console.error("找不到图表容器");
          loading.value = false;
          return;
        }
        
        // 如果图表实例已存在，先销毁
        if (graphChart) {
          graphChart.dispose();
        }
        
        // 初始化图表
        graphChart = echarts.init(graphContainer.value);
        
        // 准备节点数据，特别强调关键材料节点
        const nodes = graphData.value.nodes.map(node => {
          // 基础大小
          let symbolSize = 25;
          let category = 0;
          
          // 根据节点类型设置不同样式
          if (node.type === "Product") {
            category = 0;
          } else if (node.type === "Material") {
            category = 1;
          } else {
            category = 2;
          }
          
          // 如果是关键材料，增大节点尺寸和增加亮度
          if (node.isKeyMaterial) {
            symbolSize = 40;
            category = 3; // 使用特殊类别标记关键材料
          }
          
          return {
            ...node,
            symbolSize: symbolSize,
            category: category,
            label: {
              show: true,
              position: "right",
              fontSize: 12
            }
          };
        });
        
        // 处理关系数据
        const links = graphData.value.relationships.map(link => {
          return {
            source: link.source,
            target: link.target,
            value: link.type === "UPSTREAM_OF" ? "上游" : link.type,
            type: link.type,
            lineStyle: {
              width: 2,
              curveness: 0.2
            }
          };
        });
        
        // 图表配置
        const option = {
          title: {
            text: "关键材料识别分析图",
            subtext: "突出显示的节点为关键材料",
            top: "top",
            left: "center"
          },
          tooltip: {
            trigger: "item",
            formatter: function(params) {
              if (params.dataType === "node") {
                const node = params.data;
                let tooltipContent = `
                  <div style="font-weight:bold;margin-bottom:5px;">${node.name}</div>
                  <div>类型: ${node.type || "产品"}</div>
                `;
                
                if (node.isKeyMaterial) {
                  tooltipContent += `<div style="color:#FF5722;font-weight:bold;">关键材料</div>`;
                }
                
                if (node.description) {
                  tooltipContent += `<div>描述: ${node.description}</div>`;
                }
                
                return tooltipContent;
              } else {
                // 显示关系信息
                const sourceNode = nodes.find(n => n.id === params.data.source);
                const targetNode = nodes.find(n => n.id === params.data.target);
                const sourceName = sourceNode ? sourceNode.name : params.data.source;
                const targetName = targetNode ? targetNode.name : params.data.target;
                
                if (params.data.type === "UPSTREAM_OF") {
                  return `${sourceName} 是 ${targetName} 的上游`;
                } else {
                  return `${sourceName} → ${targetName}: ${params.data.value}`;
                }
              }
            }
          },
          legend: {
            data: ["产品", "原材料", "其他", "关键材料"],
            orient: "vertical",
            left: "left",
            top: "middle",
            textStyle: {
              fontSize: 12
            }
          },
          series: [{
            type: "graph",
            layout: "force",
            data: nodes,
            links: links,
            categories: [
              { name: "产品" },
              { name: "原材料" },
              { name: "其他" },
              { 
                name: "关键材料",
                itemStyle: {
                  color: "#FF5722"
                }
              }
            ],
            roam: true,
            label: {
              show: true,
              position: "right",
              formatter: "{b}",
              fontSize: 12
            },
            force: {
              repulsion: 200,
              gravity: 0.1,
              edgeLength: 100,
              friction: 0.6,
              layoutAnimation: true
            },
            lineStyle: {
              color: "source",
              curveness: 0.3
            },
            edgeSymbol: ["none", "arrow"],
            edgeSymbolSize: [0, 10],
            edgeLabel: {
              show: true,
              formatter: "{c}",
              fontSize: 12
            },
            emphasis: {
              focus: "adjacency",
              lineStyle: {
                width: 4
              }
            }
          }]
        };
        
        // 设置图表
        graphChart.setOption(option);
        
        // 监听窗口大小变化
        const resizeHandler = () => {
          if (graphChart) {
            graphChart.resize();
          }
        };
        window.addEventListener("resize", resizeHandler);
        
        // 确保加载状态被重置
        loading.value = false;
        
        console.log("关键材料网络图渲染完成");
      } catch (error) {
        console.error("渲染关键材料网络图失败:", error);
        loading.value = false;
        ElMessage.error("图表渲染失败: " + (error.message || "未知错误"));
      }
    };
    const decreaseRiskCount = () => {
      if (riskForm.minRiskCount > 1) {
        riskForm.minRiskCount--;
      }
    };
    const increaseRiskCount = () => {
      if (riskForm.minRiskCount < 1000) {
        riskForm.minRiskCount++;
      }
    };
    onMounted(() => {
      // 初始化时显示图表容器
      showGraph.value = true;

      // 创建一个函数来处理全屏状态变化
      const handleFullscreenChange = () => {
        isFullscreen.value = !!document.fullscreenElement || 
                            !!document.mozFullScreenElement || 
                            !!document.webkitFullscreenElement || 
                            !!document.msFullscreenElement;
        
        console.log('全屏状态变化:', isFullscreen.value);
        
        // 全屏状态变化时调整图表大小
        if (graphChart) {
          // 使用延时确保DOM已经更新
          setTimeout(() => {
            graphChart.resize();
            console.log('图表大小已调整');
          }, 200);
        }
      };
      
      // 添加各种浏览器的全屏变化事件监听
      document.addEventListener('fullscreenchange', handleFullscreenChange);
      document.addEventListener('mozfullscreenchange', handleFullscreenChange);
      document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
      document.addEventListener('msfullscreenchange', handleFullscreenChange);
      
      // 添加窗口大小变化监听器
      const handleResize = () => {
        if (graphChart) {
          graphChart.resize();
        }
      };
      window.addEventListener('resize', handleResize);
      
      // 返回清理函数
      return () => {
        // 移除事件监听器
        window.removeEventListener('resize', handleResize);
        document.removeEventListener('fullscreenchange', handleFullscreenChange);
        document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
        document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.removeEventListener('msfullscreenchange', handleFullscreenChange);
        
        // 销毁图表实例
        if (graphChart) {
          graphChart.dispose();
          graphChart = null;
        }
        
        // 清理统计图表
        if (window.statsChartCleanup) {
          window.statsChartCleanup();
          window.statsChartCleanup = null;
        }
      };
    });
    // 选择产品
    // 行业分析相关的状态
    const selectedIndustry = ref('');
    const analysisComplete = ref(false);
    const analysisData = ref(null);
    // 行业分析 - 开始分析方法
    const startAnalysis = async () => {
      console.log('开始分析按钮被点击');
      
      // 检查是否选择了行业
      if (!selectedIndustry.value) {
        ElMessage.warning('请先选择行业');
        return;
      }
      
      console.log('当前选择的行业:', selectedIndustry.value);
      
      // 设置加载状态
      loading.value = true;
      
      try {
        // 设置显示图表
        showGraph.value = true;

                // 调用API获取行业分析数据
        console.log('调用行业分析API，参数:', { industry: selectedIndustry.value });
        
        const response = await getIndustryAnalysis({ industry: selectedIndustry.value });
        console.log('行业分析API响应:', response);
        
        if (response && response.data) {
          // 更新分析数据
          analysisData.value = response.data;
          console.log('分析数据已更新:', analysisData.value);
          
          // 标记分析完成
          analysisComplete.value = true;
          
          // 初始化图表
          nextTick(() => {
            setTimeout(() => {
              initCharts();
            }, 300); // 延迟初始化图表，确保DOM已渲染
          });
        } else {
          console.error('无效的API响应格式:', response);
          ElMessage.error('获取行业分析数据失败: 无效的响应格式');
          
          // 使用测试数据作为后备
          console.log('使用测试数据作为后备');
          useTestData();
        }
      } catch (error) {
        console.error('获取行业分析数据失败:', error);
        ElMessage.error('获取行业分析数据失败: ' + (error.message || '未知错误'));
        
        // 使用测试数据
        console.log('出错后使用测试数据');
        useTestData();
      } finally {
        loading.value = false;
      }
    };
    // 使用测试数据
    const useTestData = () => {
      console.log('使用测试数据');
      
      analysisData.value = {
        distribution: [
          { value: 335, name: '制造企业' },
          { value: 310, name: '服务企业' },
          { value: 234, name: '研发企业' },
          { value: 135, name: '销售企业' },
          { value: 154, name: '综合企业' }
        ],
        techCompanies: [
          { value: 120, name: '集成电路' },
          { value: 80, name: '智能制造' },
          { value: 60, name: '电气设备' },
          { value: 40, name: '电子元件' },
          { value: 20, name: '自动化设备' }
        ],
        innovation: {
          indicators: [
            { name: '研发投入', max: 100 },
            { name: '专利数量', max: 100 },
            { name: '高学历人才', max: 100 },
            { name: '创新项目', max: 100 },
            { name: '产学研合作', max: 100 }
          ],
          values: [80, 65, 70, 60, 75]
        },
        conclusion: '该行业整体创新能力较强，研发投入占比较高，专利数量持续增长。高新技术企业主要分布在集成电路和智能制造领域。建议加强产学研合作，提升高端人才引进力度。'
      };
      
      console.log('测试数据设置完成:', analysisData.value);
      
      // 标记分析完成
      analysisComplete.value = true;
      console.log('设置analysisComplete:', analysisComplete.value);
      
      // 在下一个tick初始化图表
      nextTick(() => {
        console.log('在nextTick中准备初始化测试数据图表');
        
        // 确保DOM已经更新，图表容器已渲染
        setTimeout(() => {
          initCharts();
        }, 200);
      });
    };
    // 初始化图表
    const initCharts = () => {
      console.log('初始化图表');
      
      if (!analysisData.value) {
        console.error('没有分析数据，无法初始化图表');
        return;
      }
      
      // 图表实例变量
      let distributionChart = null;
      let techCompaniesChart = null;
      let innovationChart = null;
      let chartInstances = [];
      
      // 清理之前的图表实例
      if (chartInstances.length > 0) {
        chartInstances.forEach(chart => {
          if (chart) {
            chart.dispose();
          }
        });
        chartInstances = [];
      }
      
      // 创建企业分布图表
      const distributionDom = document.getElementById('distributionChart');
      if (distributionDom) {
        distributionChart = echarts.init(distributionDom);
        const option = {
          title: {
            text: '企业分布情况',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: analysisData.value.distribution.map(item => item.name)
          },
          series: [
            {
              name: '企业分布',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: analysisData.value.distribution,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };
        
        distributionChart.setOption(option);
        chartInstances.push(distributionChart);
      } else {
        console.error('企业分布图表容器不存在');
      }
      
      // 高新技术企业图表
      const techCompaniesEl = document.getElementById('techCompaniesChart');
      if (techCompaniesEl) {
        console.log('初始化高新技术企业图表');
        techCompaniesChart = echarts.init(techCompaniesEl);
        
        const option = {
          title: {
            text: '高新技术企业分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: analysisData.value.techCompanies.map(item => item.name),
            axisTick: {
              alignWithLabel: true
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '企业数量',
              type: 'bar',
              barWidth: '60%',
              data: analysisData.value.techCompanies.map(item => item.value)
            }
          ]
        };
        
        techCompaniesChart.setOption(option);
        chartInstances.push(techCompaniesChart);
      } else {
        console.error('高新技术企业图表容器不存在');
      }
      
      // 创新能力图表
      const innovationEl = document.getElementById('innovationChart');
      if (innovationEl) {
        console.log('初始化创新能力图表');
        innovationChart = echarts.init(innovationEl);
        
        const option = {
          title: {
            text: '创新能力评估',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          radar: {
            indicator: analysisData.value.innovation.indicators.map(item => ({
              name: item.name,
              max: item.max
            }))
          },
          series: [
            {
              name: '创新能力评估',
              type: 'radar',
              data: [
                {
                  value: analysisData.value.innovation.values,
                  name: '当前行业'
                }
              ]
            }
          ]
        };
        
        innovationChart.setOption(option);
        chartInstances.push(innovationChart);
      } else {
        console.error('创新能力图表容器不存在');
      }
      
      // 添加窗口大小变化事件监听
      const handleResize = () => {
        chartInstances.forEach(chart => {
          if (chart) chart.resize();
        });
      };
      
      window.addEventListener('resize', handleResize);
      
      // 在组件卸载时移除事件监听
      onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
        chartInstances.forEach(chart => {
          if (chart) chart.dispose();
        });
      });
    };
    // 行业企业综合分析相关方法
    const queryIndustryComprehensive = async () => {
      if (!industryComprehensiveForm.industryName) {
        ElMessage.warning('请输入行业名称');
        return;
      }
      
      loading.value = true;
      
      try {
        // 设置显示图表
        showGraph.value = true;

                // 首先获取数据
        const response = await getIndustryComprehensiveAnalysis({
          industryName: industryComprehensiveForm.industryName
        });
        
        console.log('行业企业综合分析数据:', response);
        
        // 存储数据
        comprehensiveData.value = response;
        
        // 设置showGraph为true，触发DOM渲染
        showGraph.value = true;
        
        // 等待DOM渲染完成
        await nextTick();
        
        // 使用较长的延迟确保DOM元素已完全渲染
        setTimeout(() => {
          // 检查DOM元素状态
          const companySizeElement = document.getElementById('companySizeChart');
          const comparisonElement = document.getElementById('comparisonChart');
          const patentDistElement = document.getElementById('patentDistributionChart');
          const innovationElement = document.getElementById('innovationEfficiencyChart');
          
          console.log('开始渲染图表 - 延迟检查');
          console.log('companySizeChart元素存在:', !!companySizeElement);
          console.log('comparisonChart元素存在:', !!comparisonElement);
          console.log('patentDistributionChart元素存在:', !!patentDistElement);
          console.log('innovationEfficiencyChart元素存在:', !!innovationElement);
          
          // 只有在至少有一个图表容器存在的情况下才尝试渲染
          if (companySizeElement || comparisonElement || patentDistElement || innovationElement) {
            console.log('检测到有图表容器，开始渲染...');
            renderComprehensiveCharts();
          } else {
            console.warn('未检测到任何图表容器，再次延迟尝试...');
            // 再次延迟尝试渲染
            setTimeout(() => {
              console.log('最终尝试渲染图表');
              renderComprehensiveCharts();
            }, 800);
          }
        }, 1000); // 增加延迟到1秒
        
        ElMessage.success('行业企业综合分析查询成功');
      } catch (error) {
        console.error('查询行业企业综合分析失败:', error);
        ElMessage.error('查询行业企业综合分析失败');
        showGraph.value = false;
      } finally {
        loading.value = false;
      }
    };
    // 渲染所有综合分析图表
    const renderComprehensiveCharts = () => {
      console.log('渲染综合分析图表开始');
      try {
        // 设置显示图表
        showGraph.value = true;

                if (!comprehensiveData.value) {
          console.warn('未找到综合分析数据，无法渲染图表');
          return;
        }
        // 渲染企业规模分布图表
        const companySizeDOM = document.getElementById('companySizeChart');
        if (!companySizeDOM) {
          console.warn('未找到企业规模分布图表DOM元素，跳过渲染');
        } else {
          console.log('渲染企业规模分布图表');
          renderCompanySizeChart();
        }
        // 渲染高新企业与普通企业比较图表
        const comparisonDOM = document.getElementById('comparisonChart');
        if (!comparisonDOM) {
          console.warn('未找到企业比较图表DOM元素，跳过渲染');
        } else {
          console.log('渲染高新企业与普通企业比较图表');
          renderComparisonChart();
        }
        // 渲染专利分布TOP10图表
        const patentDistributionDOM = document.getElementById('patentDistributionChart');
        if (!patentDistributionDOM) {
          console.warn('未找到专利分布图表DOM元素，跳过渲染');
        } else {
          console.log('渲染专利分布TOP10图表');
          renderPatentDistributionChart();
        }
        // 渲染创新效率TOP10图表
        const innovationEfficiencyDOM = document.getElementById('innovationEfficiencyChart');
        if (!innovationEfficiencyDOM) {
          console.warn('未找到创新效率图表DOM元素，跳过渲染');
        } else {
          console.log('渲染创新效率TOP10图表');
          renderInnovationEfficiencyChart();
        }
        console.log('渲染综合分析图表完成');
      } catch (error) {
        console.error('渲染综合分析图表发生错误:', error);
      }
    };
    // 企业规模分布图
    const renderCompanySizeChart = () => {
      console.log('开始渲染企业规模分布图表');
      try {
        // 设置显示图表
        showGraph.value = true;

                // 检查DOM元素
        const chartDom = document.getElementById('companySizeChart');
        if (!chartDom) {
          console.error('企业规模分布图表DOM元素不存在');
          return;
        }
        // 检查数据
        if (!comprehensiveData.value || !comprehensiveData.value.companySizeDistribution || 
            !Array.isArray(comprehensiveData.value.companySizeDistribution) || 
            comprehensiveData.value.companySizeDistribution.length === 0) {
          console.warn('缺少企业规模分布数据，无法渲染图表');
          chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
          return;
        }
        
        // 清空已有图表
        const chart = echarts.init(chartDom);
        
        // 准备数据 - 确保每个项目都有name和value属性
        const data = comprehensiveData.value.companySizeDistribution.map(item => {
          // 如果已经有正确的格式就直接返回
          if (item.name && (item.value !== undefined)) {
            return item;
          }
          // 否则转换为正确的格式
          return {
            name: item.size || '未知规模',
            value: item.count || 0
          };
        });
        
        console.log('企业规模分布数据:', data);
        
        // 设置图表配置
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle',
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
              fontSize: 12
            },
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '企业规模分布',
              type: 'pie',
              radius: '70%',
              center: ['60%', '50%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 6,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
                show: true,
                formatter: '{b}: {c} ({d}%)',
                fontSize: 12
              },
              emphasis: {
                label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
                  show: true,
                  fontSize: '14',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true
              },
              data: data
            }
          ]
        };
        
        // 设置配置并渲染图表
        chart.setOption(option);
        
        // 添加窗口大小变化事件监听
        window.addEventListener('resize', () => {
          chart.resize();
        });
        
        console.log('企业规模分布图表渲染完成');
      } catch (error) {
        console.error('渲染企业规模分布图表错误:', error);
      }
    };
    // 高新技术企业与普通企业对比图
    const renderComparisonChart = () => {
      console.log('开始渲染高新企业与普通企业比较图表');
      try {
        // 设置显示图表
        showGraph.value = true;

                // 检查DOM元素
        const chartDom = document.getElementById('comparisonChart');
        if (!chartDom) {
          console.error('高新企业与普通企业比较图表DOM元素不存在');
          return;
        }
        
        // 检查数据
        if (!comprehensiveData.value || !comprehensiveData.value.hightechComparison || 
            !Array.isArray(comprehensiveData.value.hightechComparison) ||
            comprehensiveData.value.hightechComparison.length === 0) {
          console.warn('缺少高新企业与普通企业比较数据，无法渲染图表');
          chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
          return;
        }
        
        // 处理比较数据
        const hightechData = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === true) || { avgEmployees: 0, avgCapital: 0, avgPatents: 0 };
        const regularData = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === false) || { avgEmployees: 0, avgCapital: 0, avgPatents: 0 };
        
        // 清空已有图表
        const chart = echarts.init(chartDom);
        
        // 设置图表配置
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          radar: {
            indicator: [
              { name: '员工人数', max: Math.max(hightechData.avgEmployees, regularData.avgEmployees) * 1.2 || 1000 },
              { name: '注册资本', max: Math.max(hightechData.avgCapital, regularData.avgCapital) * 1.2 || 5000 },
              { name: '专利数量', max: Math.max(hightechData.avgPatents, regularData.avgPatents) * 1.2 || 100 }
            ]
          },
          series: [
            {
              type: 'radar',
              data: [
                {
                  value: [
                    Math.round(hightechData.avgEmployees),
                    hightechData.avgCapital,
                    hightechData.avgPatents
                  ],
                  name: '高新技术企业',
                  areaStyle: {
                    color: 'rgba(64, 158, 255, 0.4)'
                  }
                },
                {
                  value: [
                    Math.round(regularData.avgEmployees),
                    regularData.avgCapital,
                    regularData.avgPatents
                  ],
                  name: '普通企业',
                  areaStyle: {
                    color: 'rgba(103, 194, 58, 0.4)'
                  }
                }
              ]
            }
          ]
        };
        
        // 设置配置并渲染图表
        chart.setOption(option);
        
        // 添加窗口大小变化事件监听
        window.addEventListener('resize', () => {
          chart.resize();
        });
        
        console.log('高新企业与普通企业比较图表渲染完成');
      } catch (error) {
        console.error('渲染高新企业与普通企业比较图表错误:', error);
      }
    };
    // 专利分布图
    const renderPatentDistributionChart = () => {
      console.log('开始渲染专利分布TOP10图表');
      try {
        // 设置显示图表
        showGraph.value = true;

                // 检查DOM元素
        const chartDom = document.getElementById('patentDistributionChart');
        if (!chartDom) {
          console.error('专利分布图表DOM元素不存在');
          return;
        }
        
        // 检查数据
        if (!comprehensiveData.value || !comprehensiveData.value.patentDistribution || 
            !Array.isArray(comprehensiveData.value.patentDistribution) || 
            comprehensiveData.value.patentDistribution.length === 0) {
          console.warn('缺少专利分布数据，无法渲染图表');
          chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
          return;
        }
        
        // 清空已有图表
        const chart = echarts.init(chartDom);
        
        // 只取前10条数据
        const data = comprehensiveData.value.patentDistribution.slice(0, 10);
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.company),
            axisLabel: {
              interval: 0,
              rotate: 40,
              fontSize: 10,
              width: 70,
              overflow: 'truncate'
            }
          },
          yAxis: {
            type: 'value',
            name: '专利数量'
          },
          series: [{
            name: '专利数量',
            data: data.map(item => item.patents),
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
              show: true,
              position: 'top',
              fontSize: 10
            }
          }]
        };
        
        chart.setOption(option);
        
        // 添加窗口大小变化事件监听
        window.addEventListener('resize', () => {
          chart.resize();
        });
        
        console.log('专利分布图表渲染完成');
      } catch (error) {
        console.error('渲染专利分布图表错误:', error);
      }
    };
    // 创新效率图
    const renderInnovationEfficiencyChart = () => {
      console.log('开始渲染创新效率TOP10图表');
      try {
        // 设置显示图表
        showGraph.value = true;

                // 检查DOM元素
        const chartDom = document.getElementById('innovationEfficiencyChart');
        if (!chartDom) {
          console.error('创新效率图表DOM元素不存在');
          return;
        }
        
        // 检查数据
        if (!comprehensiveData.value || !comprehensiveData.value.innovationEfficiency || 
            !Array.isArray(comprehensiveData.value.innovationEfficiency) || 
            comprehensiveData.value.innovationEfficiency.length === 0) {
          console.warn('缺少创新效率数据，无法渲染图表');
          chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
          return;
        }
        
        // 清空已有图表
        const chart = echarts.init(chartDom);
        
        // 只取前10条数据
        const data = comprehensiveData.value.innovationEfficiency.slice(0, 10);
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: function(params) {
              const item = data[params[0].dataIndex];
              return `${item.company}<br/>人均专利: ${item.efficiency.toFixed(2)}<br/>专利数: ${item.patents}<br/>员工数: ${item.employees}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.company),
            axisLabel: {
              interval: 0,
              rotate: 40,
              fontSize: 10,
              width: 70,
              overflow: 'truncate'
            }
          },
          yAxis: {
            type: 'value',
            name: '人均专利数'
          },
          series: [{
            name: '创新效率',
            type: 'bar',
            barWidth: '60%',
            data: data.map(item => item.efficiency),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#67C23A' },
                { offset: 0.5, color: '#5DAF34' },
                { offset: 1, color: '#4E9A2F' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#5DAF34' },
                  { offset: 0.7, color: '#4E9A2F' },
                  { offset: 1, color: '#449028' }
                ])
              }
            },
            label: {
            fontSize: 12, // 减小标签字体大小
            distance: 5, // 减小标签与节点的距离
              show: true,
              position: 'top',
              fontSize: 10,
              formatter: function(params) {
                return params.value.toFixed(2);
              }
            }
          }]
        };
        
        chart.setOption(option);
        
        // 添加窗口大小变化事件监听
        window.addEventListener('resize', () => {
          chart.resize();
        });
        
        console.log('创新效率图表渲染完成');
      } catch (error) {
        console.error('渲染创新效率图表错误:', error);
      }
    };
    // 获取高新技术企业与普通企业对比数据
    const getComparisonData = (isHighTech, field) => {
      if (!comprehensiveData.value || !comprehensiveData.value.hightechComparison) {
        return 0;
      }
      
      const data = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === isHighTech);
      if (!data) {
        return 0;
      }
      
      if (field === 'avgEmployees') {
        return Math.round(data.avgEmployees);
      } else if (field === 'avgCapital') {
        return data.avgCapital;
      } else if (field === 'avgPatents') {
        return data.avgPatents.toFixed(1);
      }
      
      return 0;
    };
    // 处理行业选择
    const handleIndustryComprehensiveSelect = (item) => {
      industryComprehensiveForm.industryName = item.value;
    };
    // Tab切换处理
    const handleTabClick = (tab) => {
      console.log('切换到标签:', tab.props.name);
      activeTab.value = tab.props.name;
      
      // 使用nextTick确保状态更新后再执行清理操作
      nextTick(() => {
        // 清理现有图表数据
        graphData.value = { nodes: [], relationships: [] };
        statsData.value = null;
        industryStats.value = null;
        comprehensiveData.value = null;
        console.log('已清理数据，当前活动标签:', activeTab.value);
      });
    };
    // 现在正确地放置return语句
    return {
      activeTab,
      loading,
      graphData,
      statsData,
      graphContainer,
      companyCountChart,
      employeeCountChart,
      capitalChart,
      highTechChart,
      supplyChainForm,
      industryForm,
      riskForm,
      highTechForm,
      supplyPathForm,
      productChainForm,
      industryOptions,
      queryCompanies,
      queryProducts,
      queryIndustrySearch,
      handleRiskIndustrySelect,
      handleQueryChange,
      querySupplyChain,
      queryIndustry,
      queryCompanyRisks,
      queryHighTechCompanies,
      querySupplyPath,
      queryCompanyStats,
      queryProductChain,
      identifyKeyMaterials,
      toggleFullscreen,
      isFullscreen,
      industryStats,
      getQueryTitle,
      getResultTitle,
      handleQuery,
      exportData,
      decreaseRiskCount,
      increaseRiskCount,
      Download,
      FullScreen,
      Close,
      Connection,
      OfficeBuilding,
      Warning,
      DataAnalysis,
      PieChart,
      Goods,
      resetProductChainForm,
      permissionStatus,
      hasPermission,
      selectedIndustry,
      analysisComplete,
      analysisData,
      startAnalysis,
      useTestData,
      initCharts,
      industryComprehensiveForm,
      comprehensiveData,
      queryIndustryComprehensive,
      renderComprehensiveCharts,
      renderCompanySizeChart,
      renderComparisonChart,
      renderPatentDistributionChart,
      renderInnovationEfficiencyChart,
      getComparisonData,
      handleIndustryComprehensiveSelect,
      handleTabClick,
      showGraph
    };
  }
}
</script>
<style scoped>
.graph-analysis-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 优化顶部tabs样式 */
.graph-analysis-container :deep(.el-tabs) {
  margin-bottom: 25px;
}

.graph-analysis-container :deep(.el-tabs__header) {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  border-bottom: none;
}

.graph-analysis-container :deep(.el-tabs__nav-wrap) {
  display: flex;
  justify-content: center;
}

.graph-analysis-container :deep(.el-tabs__nav) {
  background-color: #f0f5ff;
  border-radius: 24px;
  box-shadow: 0 8px 24px rgba(50, 50, 93, 0.1), 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 8px;
  border: none;
  position: relative;
  z-index: 1;
}

.graph-analysis-container :deep(.el-tabs__item) {
  height: 48px;
  line-height: 48px;
  min-width: 120px;
  font-size: 14px;
  color: #606266;
  border-radius: 20px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  padding: 0 20px;
  margin: 0 6px;
  border: none;
  position: relative;
  overflow: hidden;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
  border: 1px solid rgba(0, 0, 0, 0.08);
}

.graph-analysis-container :deep(.el-tabs__item.is-active) {
  color: #ffffff;
  background-color: #409EFF;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  border: none;
}

.graph-analysis-container :deep(.el-tabs__item:hover:not(.is-active)) {
  color: #409EFF;
  background-color: rgba(64, 158, 255, 0.1);
}

.graph-analysis-container :deep(.el-tabs__active-bar) {
  display: none;
}

.tab-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  white-space: nowrap;
}

.tab-label .el-icon {
  margin-right: 4px;
  font-size: 18px;
  vertical-align: middle;
}

/* 增加样式，在企业风险查询时隐藏额外的数据表格 */
.graph-content .risk-table-hidden {
  display: none !important;
}
/* 企业风险查询时隐藏特定统计内容 */
.stats-overview .risk-stat-hidden {
  display: none !important;
}
/* 防止重复显示统计信息 */
.stats-overview[data-tab="companyRisks"] .stat-card:has(.statistic-item[title="高新技术企业数量"]) {
  display: none !important;
}
.stats-overview[data-tab="companyRisks"] .stat-card:has(.statistic-item[title="平均注册资本"]) {
  display: none !important;
}
/* 修改其他样式... */
.main-content-layout {
  display: flex;
  gap: 15px;
  margin-top: 15px;
}
@media (max-width: 768px) {
  .main-content-layout {
    flex-direction: column;
  }
}
.query-card {
  width: 320px;
  min-width: 320px;
  height: fit-content;
  flex-shrink: 0;
}
.query-type-selector {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}
.query-type-buttons {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}
.query-type-buttons :deep(.el-radio-button__inner) {
  padding: 12px 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 14px;
  border: none;
  background-color: #fff;
  color: #606266;
  transition: all 0.3s ease;
}
.query-type-buttons :deep(.el-radio-button__inner:hover) {
  color: #409EFF;
  background-color: #ecf5ff;
}
.query-type-buttons :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: #409EFF;
  box-shadow: 0 0 0 1px #409EFF;
  color: #fff;
}
.main-content-layout {
  display: flex;
  gap: 16px;
  height: calc(100% - 64px);
  overflow: hidden;
}
.query-card {
  flex: 0 0 300px;
  min-width: 270px;
  max-width: 360px;
  overflow-y: auto;
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 8px;
}
.graph-card {
  flex: 1;
  overflow: auto; /* 改为auto允许内容溢出时滚动 */
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
}
.graph-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}
.graph-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}
.graph-controls .control-button {
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 5px;
}
.graph-visualization {
  flex: 1;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  background-color: #fafbfc;
}
.graph-container {
  width: 100%;
  height: 600px;
  min-height: 500px;
}
.form-input {
  width: 100%;
  margin-bottom: 5px;
}
.form-input :deep(.el-input__wrapper),
.form-input :deep(.el-select__wrapper) {
  border-radius: 6px;
  box-shadow: 0 0 0 1px #dcdfe6;
  transition: all 0.3s ease;
}
.form-input :deep(.el-input__wrapper:hover),
.form-input :deep(.el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}
.form-input :deep(.el-input__wrapper:focus-within),
.form-input :deep(.el-select__wrapper:focus-within) {
  box-shadow: 0 0 0 1px #409EFF;
}
.form-slider {
  margin-top: 8px;
  height: 34px;
  width: 100%;
  max-width: 600px;
}
.form-slider :deep(.el-slider__runway) {
  height: 6px;
  background-color: #e4e7ed;
}
.form-slider :deep(.el-slider__bar) {
  height: 6px;
  background-color: #409EFF;
}
.form-slider :deep(.el-slider__button) {
  width: 16px;
  height: 16px;
  border: 2px solid #409EFF;
  background-color: #fff;
}
.risk-count-input {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 8px;
  gap: 10px;
}
.count-button {
  width: 40px;
  height: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  border-radius: 4px;
}
.count-display {
  width: 80px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #303133;
  box-shadow: 0 0 0 1px #dcdfe6;
}
.query-button {
  min-width: 120px;
  padding: 10px 24px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
  border-radius: 6px;
}
.reset-button {
  margin-left: 10px;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
  border-radius: 6px;
}
.direction-selector {
  margin-top: 12px;
}
.direction-radio-group {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.direction-radio-group :deep(.el-radio) {
  margin-right: 0;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}
.direction-radio-group :deep(.el-radio__label) {
  font-size: 14px;
}
.empty-graph {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: #fafafa;
  border-radius: 8px;
  padding: 24px;
}
/* 优化行业统计区域的样式 */
.stats-overview {
  background-color: #f9fafc;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  flex-shrink: 0;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
}
.statistic-item :deep(.el-statistic__head) {
  color: #909399;
  font-size: 14px;
  margin-bottom: 8px;
}
.statistic-item :deep(.el-statistic__content) {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}
.statistic-item :deep(.el-statistic__value) {
  color: #409EFF;
  font-weight: 600;
}
.stats-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 20px;
  height: calc(100% - 30px);
  padding: 10px;
  overflow: auto; /* 允许统计容器滚动 */
}
.chart-container {
  min-height: 300px;
  height: 350px; /* 固定高度确保图表显示完整 */
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
.stats-query-info {
  padding: 10px 0;
}
.stats-alert {
  margin-bottom: 20px;
  border-radius: 6px;
}
.stats-alert :deep(.el-alert__title) {
  font-size: 14px;
  font-weight: 500;
}
.stats-alert :deep(.el-alert__description) {
  margin-top: 6px;
  font-size: 12px;
}
.stats-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-top: 20px;
}
.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9fafc;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}
.feature-item:hover {
  background-color: #ecf5ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #c6e2ff;
}
.feature-icon {
  font-size: 24px;
  color: #409EFF;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 10px;
  border-radius: 8px;
}
.feature-text h4 {
  margin: 0;
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}
.product-item {
  padding: 8px 0;
}
.product-description {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
/* 响应式布局调整 */
@media (max-width: 1200px) {
  .main-content-layout {
    flex-direction: column;
  }
  
  .query-card {
    flex: 0 0 auto;
    max-width: 100%;
    min-width: 100%;
    margin-bottom: 16px;
  }
  
  .graph-card {
    flex: 1;
    min-height: 600px; /* 增加图表卡片的最小高度 */
  }
  
  .stats-container {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(4, 350px); /* 在小屏幕上调整为单列，每个图表固定高度 */
    gap: 16px;
    height: auto; /* 高度自适应 */
  }
}
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .graph-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .graph-container {
    min-height: 400px;
    height: 400px;
  }
  
  .chart-container {
    min-height: 300px;
    height: 300px; /* 在小屏幕上减小图表高度 */
  }
  
  .empty-graph {
    height: 300px;
  }
  
  .stats-features {
    grid-template-columns: 1fr;
  }
  
  .stats-overview .el-row {
    flex-direction: column;
  }
  
  .stats-overview .el-col {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .query-type-buttons :deep(.el-radio-button__inner) {
    padding: 10px 16px;
    font-size: 12px;
  }
}
/* 其他现有样式保持不变 */
.query-button {
  min-width: 120px;
}
.comprehensive-analysis {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
}
.stat-cards {
  margin-bottom: 0;
}
.stat-card, .chart-card {
  transition: all 0.3s ease;
  height: 100%;
}
.stat-card:hover, .chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
.stat-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}
.chart-card {
  height: 350px;
  display: flex;
  flex-direction: column;
}
.chart-card .stat-title {
  margin-bottom: 5px;
}
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 350px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
.empty-stats {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 350px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
.empty-stats .el-empty {
  margin: 0;
}

/* 现代化顶部标签页样式 */
.main-tabs-container {
  margin-bottom: 30px;
  padding: 5px;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.07);
  position: relative;
  overflow: hidden;
}

.main-tabs-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.8), transparent);
  z-index: 1;
}

.main-tabs-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 6px;
  position: relative;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
}

.main-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 20px;
  border-radius: 10px;
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  gap: 10px;
  z-index: 1;
  margin: 0 3px;
}

.main-tab::after {
  content: '';
  position: absolute;
  bottom: -3px;
  left: 50%;
  width: 0;
  height: 3px;
  background: var(--el-color-primary);
  transition: all 0.3s ease;
  transform: translateX(-50%);
  opacity: 0;
  border-radius: 3px;
}

.main-tab:hover:not(.active) {
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

.main-tab:hover:not(.active)::after {
  width: 30%;
  opacity: 0.5;
}

.main-tab.active {
  color: white;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  box-shadow: 0 6px 15px rgba(var(--el-color-primary-rgb), 0.25);
  transform: translateY(-1px);
}

.main-tab.active::after {
  width: 70%;
  opacity: 1;
}

.tab-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.tab-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 768px) {
  .main-tab {
    padding: 12px 8px;
    font-size: 13px;
    flex-direction: column;
    gap: 5px;
  }
  
  .tab-icon {
    font-size: 18px;
  }
}
</style> 
